using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Schema;
using NUnit.Framework;
using Xtee.Core;
using Xtee.CodeDom.MetaInfo;
using System.Xml;
using Xtee.CodeDom.Test;
using Xtee.Core.Services.Description;

namespace Xtee.CodeDom.Test
{
    [SetUpFixture]
    public class GlobalSetup
    {
        public static  string TempOutput
        {
            get
            {
                return Environment.GetEnvironmentVariable("TEMP") + @"\codegen\";
            }
        }
        public static string ComplextTypesSchemaPath = @"..\..\Resources\ComplexTypes\ComplexTypes.xsd";
        protected static void SchemaReadError(object sender, ValidationEventArgs arguments)
        {
            Console.WriteLine(arguments.Exception.ToString());
        }

        [SetUp]
        public void Setup()
        {

            if (!Directory.Exists(TempOutput))
                Directory.CreateDirectory(TempOutput);
             
            var schemas = GetSchemas();
            var schema = schemas.First();
            var targetNamespace = schemas.First().Namespaces.ToArray().ToList().First(x => x.Namespace == schema.TargetNamespace);
            Resolver = new SchemaObjectResolver(targetNamespace, new XmlSchemaSet(), new Description(schemas.ToList()));
            new SchemaSetCompiler(Resolver).Compile();
        }

        public static SchemaObjectResolver Resolver;

        private IEnumerable<XmlSchema> GetSchemas()
        {
            var targetSchema = GetSchema(ComplextTypesSchemaPath);  
            yield return targetSchema ;
            //yield return GetSchema(@"..\..\Resources\SimpleTypes.xsd"); we load these from xsd file with include
            //yield return GetSchema(@"..\..\Resources\SimpleTypes\SimpleTypes.xsd");
            //yield return GetSchema(@"..\..\Resources\SimpleTypes\ListTypes.xsd");
            //yield return GetSchema(@"..\..\Resources\SimpleTypes\UnionTypes.xsd"); 
        }

        private XmlSchema GetSchema(string path)
        {
            using (var str = File.OpenRead(path))
            {
                return XmlSchema.Read(str, SchemaReadError);
            } 
        } 
    } 
}
namespace Xtee.CodeDom
{
    internal static class ConversionExtensions
    {
        public static ClassInfo ToClassInfo(this XmlSchemaObject obj)
        {
            return obj.ToClassInfo(GlobalSetup.Resolver);
        }
        public static XmlSchemaType ToClassInfo(this XmlQualifiedName obj)
        {
            return obj.ToSchemaType(GlobalSetup.Resolver);
        }
    }
}